const fileManager = require('./file-manager');

class DataOrganizer {
    constructor() {
        this.messageIndex = new Map();
        this.logger = this.getLogger();
    }

    getLogger() {
        try {
            return require('../utils/logger');
        } catch (error) {
            return {
                info: (...args) => console.log('[INFO]', ...args),
                error: (...args) => console.error('[ERROR]', ...args),
                warn: (...args) => console.warn('[WARN]', ...args),
                debug: (...args) => console.log('[DEBUG]', ...args)
            };
        }
    }

    // 保存消息数据
    async saveMessage(payload) {
        try {
            const messageData = {
                ...payload,
                _received_at: new Date().toISOString(),
                _version: '1.0'
            };

            // 保存为 JSON 文件
            const filename = `message_${payload.message_id || Date.now()}.json`;
            await fileManager.saveText(
                JSON.stringify(messageData, null, 2),
                filename
            );

            // 更新索引
            if (payload.message_id) {
                this.messageIndex.set(payload.message_id, {
                    filename: filename,
                    timestamp: messageData._received_at,
                    type: payload.message_type,
                    user_id: payload.user_id,
                    group_id: payload.group_id
                });
            }

            this.logger.debug(`消息数据已保存: ${filename}`);
            return true;
        } catch (error) {
            this.logger.error('保存消息数据失败:', error);
            throw error;
        }
    }

    // 保存通知数据
    async saveNotice(payload) {
        try {
            const noticeData = {
                ...payload,
                _received_at: new Date().toISOString(),
                _type: 'notice'
            };

            const filename = `notice_${payload.notice_type}_${Date.now()}.json`;
            await fileManager.saveText(
                JSON.stringify(noticeData, null, 2),
                filename
            );

            this.logger.debug(`通知数据已保存: ${filename}`);
            return true;
        } catch (error) {
            this.logger.error('保存通知数据失败:', error);
            throw error;
        }
    }

    // 保存请求数据
    async saveRequest(payload) {
        try {
            const requestData = {
                ...payload,
                _received_at: new Date().toISOString(),
                _type: 'request'
            };

            const filename = `request_${payload.request_type}_${Date.now()}.json`;
            await fileManager.saveText(
                JSON.stringify(requestData, null, 2),
                filename
            );

            this.logger.debug(`请求数据已保存: ${filename}`);
            return true;
        } catch (error) {
            this.logger.error('保存请求数据失败:', error);
            throw error;
        }
    }

    // 根据消息ID获取消息数据
    async getMessage(messageId) {
        try {
            const index = this.messageIndex.get(messageId);
            if (!index) {
                throw new Error(`消息ID未找到: ${messageId}`);
            }

            const data = await fileManager.readFile('texts', index.filename);
            return JSON.parse(data.toString());
        } catch (error) {
            this.logger.error(`获取消息数据失败 [${messageId}]:`, error);
            throw error;
        }
    }

    // 获取最近的消息
    async getRecentMessages(limit = 50) {
        try {
            const files = await fileManager.listFiles('texts', { withStats: true });
            
            // 过滤消息文件并按时间排序
            const messageFiles = files
                .filter(file => file.name.startsWith('message_'))
                .sort((a, b) => b.modified - a.modified)
                .slice(0, limit);

            const messages = [];
            for (const file of messageFiles) {
                try {
                    const data = await fileManager.readFile('texts', file.name);
                    messages.push(JSON.parse(data.toString()));
                } catch (error) {
                    this.logger.warn(`读取消息文件失败: ${file.name}`, error);
                }
            }

            return messages;
        } catch (error) {
            this.logger.error('获取最近消息失败:', error);
            throw error;
        }
    }

    // 统计消息数据
    async getMessageStats() {
        try {
            const files = await fileManager.listFiles('texts');
            
            const stats = {
                total: 0,
                byType: {},
                byDate: {}
            };

            for (const filename of files) {
                if (filename.startsWith('message_')) {
                    stats.total++;
                    
                    try {
                        const data = await fileManager.readFile('texts', filename);
                        const message = JSON.parse(data.toString());
                        
                        // 按消息类型统计
                        const type = message.message_type || 'unknown';
                        stats.byType[type] = (stats.byType[type] || 0) + 1;
                        
                        // 按日期统计
                        const date = new Date(message._received_at).toISOString().split('T')[0];
                        stats.byDate[date] = (stats.byDate[date] || 0) + 1;
                        
                    } catch (error) {
                        this.logger.warn(`分析消息文件失败: ${filename}`, error);
                    }
                }
            }

            return stats;
        } catch (error) {
            this.logger.error('统计消息数据失败:', error);
            throw error;
        }
    }

    // 清理旧消息数据
    async cleanupOldMessages(maxAge = 30 * 24 * 60 * 60 * 1000) { // 默认30天
        const cutoffTime = Date.now() - maxAge;
        let cleanedCount = 0;

        try {
            const files = await fileManager.listFiles('texts', { withStats: true });
            
            for (const file of files) {
                if (file.name.startsWith('message_') && file.created.getTime() < cutoffTime) {
                    try {
                        await fileManager.deleteFile('texts', file.name);
                        cleanedCount++;
                    } catch (error) {
                        this.logger.warn(`清理消息文件失败: ${file.name}`, error);
                    }
                }
            }
            
            this.logger.info(`清理完成，共删除 ${cleanedCount} 个旧消息文件`);
            return cleanedCount;
        } catch (error) {
            this.logger.error('清理旧消息数据失败:', error);
            throw error;
        }
    }
}

module.exports = new DataOrganizer();